<template>
  <a-modal
    v-model:visible="visible"
    :title="editId ? '修改关键词' : '新增关键词'"
    @cancel="onClose"
    width="800px"
  >
    <div class="container">
      <a-form :label-col="{ span: 6 }" ref="formRef" :model="formState">
        <a-form-item
          style="margin-bottom: 10px !important"
          label="关键词规则名称"
          name="extractionWord"
          :rules="[
            {
              required: true,
              message: '请输入关键词规则名称',
              trigger: 'blur',
            },
          ]"
        >
          <a-input
            v-model:value="formState.extractionWord"
            placeholder="请输入关键词规则名称"
            show-count
            :maxlength="30"
            style="width: 70%; margin-right: 10px"
          ></a-input>
          <a-tooltip>
            <template #title>关键词规则名称为了方便使用的时候快速查找</template>
            <info-circle-outlined
              style="font-size: 20px; color: var(--ss-info-color)"
            />
          </a-tooltip>
        </a-form-item>
        <a-form-item
          style="margin-bottom: 10px !important; margin-top: 20px !important"
          label="主关键词"
          name="masterKeyword"
          :rules="{
            required: true,
            message: '请输入主关键词',
            trigger: 'blur',
          }"
        >
          <a-textarea
            placeholder="请输入内容方可换行"
            class="textarea"
            style="width: 70%"
            v-model:value="formState.masterKeyword"
            @input="MasterKeywordInput($event)"
            :auto-size="{ minRows: 6, maxRows: 10 }"
            allowClear
          ></a-textarea>
        </a-form-item>
        <a-row>
          <a-col :offset="6">
            <div class="tip_rules">
              每行一个词，建议3-10个词，每个词10个字之内
            </div>
            <div class="tip_type">一般填行业，例如：二手房，公租房</div>
          </a-col>
        </a-row>

        <a-form-item
          label="前缀(可填品牌或地区)"
          style="margin-top: 20px; margin-bottom: 10px !important"
          name="prefix"
          :rules="[
            {
              required: true,
              message: '请输入前缀词',
              trigger: 'blur',
            },
          ]"
        >
          <a-textarea
            placeholder="请输入内容方可换行"
            class="textarea"
            style="width: 70%"
            v-model:value="formState.prefix"
            @input="PrefixInput($event)"
            :auto-size="{ minRows: 5, maxRows: 5 }"
          ></a-textarea>
        </a-form-item>
        <a-row>
          <a-col :offset="6">
            <div class="tip_rules">
              每行一个词，建议3-5个词，每个词10个字之内
            </div>
            <div class="tip_type">
              可设置地区或者品牌，例如：广州，南京，某某品牌
            </div>
          </a-col>
        </a-row>
        <a-form-item
          label="后缀词"
          style="margin-top: 20px; margin-bottom: 10px !important"
          name="suffix"
          :rules="[
            {
              required: true,
              message: '请输入后缀词',
              trigger: 'blur',
            },
          ]"
        >
          <a-textarea
            placeholder="请输入内容方可换行"
            class="textarea"
            style="width: 70%"
            v-model:value="formState.suffix"
            @input="SuffixInput($event)"
            :auto-size="{ minRows: 5, maxRows: 5 }"
          ></a-textarea>
        </a-form-item>
        <a-row>
          <a-col :offset="6">
            <div class="tip_rules">
              每行一个词，建议3-5个词，每个词10个字之内
            </div>
            <div class="tip_type">例如：哪里好，价格，划算，门店，多少钱</div>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <template #footer>
      <a-button @click="onClose">取消</a-button>
      <a-button @click="handleSubmit" type="primary" :loading="loading"
        >确定</a-button
      >
    </template>
  </a-modal>
</template>

<script>
import { message } from "ant-design-vue";
import {
  defineComponent,
  reactive,
  ref,
  onMounted,
  watch,
  computed,
  toRefs,
} from "vue";
import request from "@/common/utils/request";
import { useRouter } from "vue-router";
import { InfoCircleOutlined } from "@ant-design/icons-vue";
export default defineComponent({
  components: {
    InfoCircleOutlined,
  },
  setup(props, context) {
    const state = reactive({
      masterKeywordList: [],
      prefixList: [],
      suffixList: [],
      loading: false,
      visible: false,
      editId: "",
    });
    const formState = reactive({
      masterKeyword: "", //主关键词
      prefix: "", //前缀
      suffix: "", //后缀
      extractionWord: "", //提取词
    });
    const showModal = (info) => {
      state.visible = true;
      if (info) {
        state.editId = info.id;
        state.masterKeywordList = info.master_keyword; //主关键词数组
        state.prefixList = info.prefix; //前缀数组
        state.suffixList = info.suffix; //后缀数组
        formState.masterKeyword = info.master_keyword.join("\n"); //主关键词
        formState.prefix = info.prefix.join("\n"); //前缀
        formState.suffix = info.suffix.join("\n"); //后缀
        formState.extractionWord = info.extraction_word; //提取词
      }
    };
    const initData = () => {
      formRef.value && formRef.value.resetFields();
      state.editId = null;
      state.masterKeywordList = [];
      state.prefixList = [];
      state.suffixList = [];
      formState.masterKeyword = "";
      formState.prefix = "";
      formState.suffix = "";
      formState.extractionWord = "";
    };
    // 主关键词input事件
    const MasterKeywordInput = (e) => {
      if (!e.target.value.trim()) {
        // 判断如果什么都没填，或只填了空白字符，则清空输入并返回
        formState.masterKeyword = "";
        return;
      }
      // 分割每行内容
      let lines = e.target.value && e.target.value.split("\n");
      lines = lines.map((line) => line.slice(0, 10)); //截取每行10个字符
      //截取前5行
      if (lines.length > 10) {
        message.warning("最多只能输入10行");
        lines = lines.slice(0, 10);
      }
      if (lines.length) {
        // 过滤掉空行
        state.masterKeywordList = lines.filter((line) => line.trim() !== "");
        // console.log(state.masterKeywordList)
      }
      formState.masterKeyword = lines.join("\n");
    };
    //前缀input事件
    const PrefixInput = (e) => {
      if (!e.target.value.trim()) {
        // 判断如果什么都没填，或只填了空白字符，则清空输入并返回
        formState.prefix = "";
        return;
      }
      // 分割每行内容
      let lines = e.target.value && e.target.value.split("\n");
      lines = lines.map((line) => line.slice(0, 10)); //截取每行10个字符
      //截取前5行
      if (lines.length > 5) {
        message.warning("最多只能输入5行");
        lines = lines.slice(0, 5);
      }
      if (lines.length) {
        // 过滤掉空行
        state.prefixList = lines.filter((line) => line.trim() !== "");
        // console.log(state.prefixList)
      }
      formState.prefix = lines.join("\n");
    };
    // 后缀input事件
    const SuffixInput = (e) => {
      if (!e.target.value.trim()) {
        // 判断如果什么都没填，或只填了空白字符，则清空输入并返回
        formState.suffix = "";
        return;
      }
      // 分割每行内容
      let lines = e.target.value.split("\n");
      lines = lines.map((line) => line.slice(0, 10)); //截取每行10个字符
      //截取前5行
      if (lines.length > 5) {
        message.warning("最多只能输入5行");
        lines = lines.slice(0, 5);
      }
      if (lines.length) {
        // 过滤掉空行
        state.suffixList = lines.filter((line) => line.trim() !== "");
        // console.log(state.suffixList)
      }
      formState.suffix = lines.join("\n");
      // console.log(formState.suffix)
    };
    const formRef = ref();
    const router = useRouter();
    const handleSubmit = () => {
      formRef.value &&
        formRef.value
          .validate()
          .then(() => {
            if (formState.extractionWord.trim().length <= 0) {
              return message.warning("关键词规则名称不能为空");
            }
            let params = {
              master_keyword: state.masterKeywordList,
              prefix: formState.prefix.split('\n'),
              suffix: formState.suffix.split('\n'),
              extraction_word: formState.extractionWord.trim(),
            };
            state.loading = true;
            if (state.editId) {
              params.id = state.editId;
              request
                .put("/work_ai", "/user/filmrelease/ai/keyword/update", params)
                .then((res) => {
                  state.loading = false;
                  if (res && res.result) {
                    message.success("修改成功");
                    state.visible = false;
                    context.emit("success");
                    initData();
                  }
                })
                .catch((err) => {
                  state.loading = false;
                });
            } else {
              request
                .post(
                  "/work_ai",
                  "/user/filmrelease/ai/generate_keyword",
                  params
                )
                .then((res) => {
                  state.loading = false;
                  if (res && res.result) {
                    message.success("添加成功");
                    state.visible = false;
                    context.emit("success");
                    initData();
                  }
                })
                .catch((err) => {
                  state.loading = false;
                });
            }
          })
          .catch((err) => {
            state.loading = false;
          });
    };
    const onClose = () => {
      state.visible = false;
      initData();
    };
    return {
      ...toRefs(state),
      formState,
      MasterKeywordInput,
      PrefixInput,
      SuffixInput,
      formRef,
      handleSubmit,
      router,
      showModal,
      onClose,
      initData,
    };
  },
});
</script>

<style lang="less" scoped>
.container {
  padding: 10px;

  .tip_rules {
    color: #b1aeae;
    // color: red;
    font-size: 12px;
  }

  .tip_type {
    margin-top: 5px;
    // color: #b1aeae;
    font-size: 12px;
  }

  .textarea {
    resize: none;

    &::-webkit-scrollbar {
      width: 8px;
      /* 滚动条的宽度 */
      height: 10px;
      /* 滚动条的高度，垂直滚动条可能用得上 */
      display: none;
    }

    &::-webkit-scrollbar-thumb {
      background: #888;
      /* 滑块的背景颜色 */
      border-radius: 10px;
      /* 滑块的圆角 */
    }
  }
}
</style>
